package com.evil.common.mongo.util;

import cn.hutool.core.collection.CollectionUtil;
import com.evil.common.core.entity.Order;
import com.evil.common.core.entity.PageModel;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyang
 * @date 2025-01-03 16:45
 */
public class PageableUtil {

    public static <T> Pageable build(PageModel<T> model) {
        List<Sort.Order> sortOrders = model.getOrders().stream().map(PageableUtil::buildSort).collect(Collectors.toList());
        return PageRequest.of(model.getPageNum(), model.getPageSize(), Sort.by(sortOrders));
    }

    public static Sort buildSorts(List<Order> orders) {
        if (CollectionUtil.isEmpty(orders)) {
            return Sort.unsorted();
        }
        return Sort.by(orders.stream().map(PageableUtil::buildSort).collect(Collectors.toList()));
    }

    public static Sort.Order buildSort(Order order) {
        Sort.Direction direction = order.isDesc() ? Sort.Direction.DESC : Sort.Direction.ASC;
        return new Sort.Order(direction, order.getField());
    }
}
